<template>
  <div>
    <div class="member_search_wrap">
      <el-autocomplete
        ref="searchValueRef"
        v-model="searchValue"
        :fetch-suggestions="queryMemberAsync"
        style="width: 100%"
        :trigger-on-focus="false"
        select-when-unmatched
        :placeholder="placeholder"
        @select="handleMemberSelect"
      >
        <el-button slot="append" @click="clear">清空</el-button>
      </el-autocomplete>
      <el-button
        v-if="isShowChooseBtn"
        class="ml20"
        type="primary"
        @click="openModal"
      >选择会员</el-button>
    </div>
    <el-dialog
      title="选择会员"
      :visible.sync="isShowMemberList"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
      :append-to-body="true"
      width="1000px"
    >
      <div>
        <div class="df_ac mb20">
          <el-input
            v-model="modalSearchValue"
            class="w400"
            :placeholder="placeholder"
            @keyup.enter.native="queryList"
          >
            <!-- <el-button slot="append" icon="el-icon-search" @click="queryList()" /> -->
          </el-input>
          <el-button
            class="ml10"
            type="primary"
            @click="queryList()"
          >查询</el-button>
        </div>
        <el-table
          ref="table"
          v-loading="listLoading"
          :data="list"
          element-loading-text="Loading"
          border
          fit
          :header-row-class-name="'table-header'"
          class="doumee-element-table doumee-element-tableb"
          @row-click="rowClick"
        >
          <el-table-column label="会员信息" min-width="200" align="center">
            <template slot-scope="scope">
              <span class="name">{{ scope.row.nickName }}</span>
              <span v-if="scope.row.phone" class="phone">
                - {{ scope.row.phone }}</span>
              <span v-if="scope.row.number" class="number">
                - {{ scope.row.number }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column
            align="center"
            label="会员卡号"
            prop="number"
            min-width="80"
          /> -->
          <el-table-column
            align="center"
            label="会员等级"
            prop="cardName"
            show-overflow-tooltip
            min-width="100"
          />
          <!-- <el-table-column
            v-if="type === '20'"
            align="center"
            label="会员折扣"
            show-overflow-tooltip
            min-width="80"
          >
            <template v-slot="scope">
              {{ scope.row.discount }}
            </template>
          </el-table-column> -->
          <el-table-column
            align="center"
            label="充值余额"
            show-overflow-tooltip
            prop="remainingMoney"
            min-width="80"
          />
          <el-table-column
            align="center"
            label="赠送余额"
            show-overflow-tooltip
            prop="remainingGiveMoney"
            min-width="80"
          />
          <el-table-column
            label="创建时间"
            prop="createTime"
            min-width="160"
            align="center"
          />
        </el-table>
        <Pagination
          :total="totalCount"
          :page="pagination.page"
          @current-change="currentChange"
          @SizeChange="handleSizeChange"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowMemberList = false">取消</el-button>
        <el-button
          v-preventReClick
          type="primary"
          @click="isShowMemberList = false"
        >确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { memberListb, memberDetailInfo } from '@/api'
import dayjs from 'dayjs'
import store from '@/store'
import { debounce } from '@/utils/debounce'

import Pagination from '@/components/paginations'
export default {
  components: {
    Pagination
  },
  props: {
    placeholder: {
      type: String,
      default: '会员昵称/手机号/卡号'
    },
    isShowChooseBtn: {
      type: Boolean,
      default: () => true
    },
    type: { // (10: 商品折扣  20: 订场折扣 30: 门票折扣 40: 套餐折扣 50：活动折扣 60：课程折扣)
      type: String,
      default: 'default'
    }
  },
  data() {
    return {
      searchValue: '',
      isShowMemberList: false,
      modalSearchValue: '',
      list: [],
      totalCount: 0,
      pagination: {
        rows: 10,
        page: 1,
        firstQueryTime: dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')
      },
      listLoading: false,

      modalDialog: store.getters.dialog,
      discountMap: {
        10: '商品折扣',
        20: '订场折扣',
        30: '门票折扣',
        40: '套餐折扣',
        50: '活动折扣',
        60: '课程折扣'
      }
    }
  },
  created() {
    // (10: 商品折扣  20: 订场折扣 30: 门票折扣 40: 套餐折扣 50：活动折扣 60：课程折扣)
  },
  methods: {
    queryMemberAsync: debounce(function(queryString, cb) {
      if (!queryString) {
        this.$emit('clear')
      }
      const data = {
        pagination: {
          firstQueryTime: dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss'),
          page: 1,
          rows: 20
        },
        param: {
          keyword: queryString
        }
      }
      memberListb(data).then((res) => {
        if (res.errorCode !== '000000') return
        const result = res.recordList
        result.forEach((item) => {
          item.value = item.nickName
          if (item.phone) {
            item.value += '-' + item.phone
          }
          if (item.number) {
            item.value += '（' + item.number + '）'
          }
        })
        cb(result)
      })
    }, 500),
    clearSearch() {
      this.searchValue = ''
      this.modalSearchValue = ''
    },
    handleMemberSelect(item) {
      memberDetailInfo({ param: { memberId: item.id }}).then((res) => {
        if (res.errorCode !== '000000') return
        const obj = res.record || {}
        obj.searchValue = this.searchValue
        this.$emit('select', obj)
      })
    },
    clear() {
      this.searchValue = ''
      setTimeout(() => {
        this.$refs.searchValueRef.focus()
      })
      this.$emit('clear')
    },
    rowClick(item) {
      memberDetailInfo({ param: { memberId: item.id }}).then((res) => {
        if (res.errorCode !== '000000') return
        const obj = res.record || {}
        this.searchValue = obj.nickName
        obj.searchValue = this.modalSearchValue
        if (item.phone) {
          this.searchValue += '-' + item.phone
        }
        if (item.number) {
          this.searchValue += '（' + item.number + '）'
        }
        this.$emit('select', obj)
      })
      this.isShowMemberList = false
    },
    getList() {
      const { pagination, modalSearchValue } = this
      this.listLoading = true
      memberListb({ pagination, param: { keyword: modalSearchValue }}).then((res) => {
        this.listLoading = false
        if (res.errorCode !== '000000') return
        this.list = res.recordList
        this.list.forEach(item => {
          if (item.cardName && item.discountDoLIst) {
            item.discount = ''
            item.discountDoLIst.forEach(card => {
              if (card.discountType === this.type) {
                item.discount = card.discount
              }
            })
          }
        })
        this.totalCount = res.totalCount
      }, () => {
        this.listLoading = false
      })
    },
    openModal() {
      this.modalSearchValue = ''
      this.queryList()
      this.isShowMemberList = true
    },
    queryList() {
      this.pagination.page = 1
      this.getList()
    },
    currentChange(val) {
      this.pagination.page = val
      this.getList()
    },
    handleSizeChange(val) {
      this.pagination.rows = val
      this.getList()
    }
  }
}
</script>

<style lang="scss" scoped>
.member_search_wrap {
  display: flex;
  ::v-deep .el-input__validateIcon{
    display: none !important;
  }
}
</style>
